package main

import (
	"database/sql"
	"fmt"
	"io/ioutil"
	"log"
	"strconv"
	"strings"

	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func initializeDatabase() (err error) {
	//data source name
	//用户名@密码@协议(ip:port)/数据库
	dsn := "root:PENCS*3768SJ@tcp(9.135.220.143:3306)/db_teg_abolish?charset=utf8mb4&parseTime=True&loc=Local"
	db, err = sql.Open("mysql", dsn)
	if err != nil {
		return
	}

	//资源释放
	//defer db.Close()

	//尝试建立连接
	if err = db.Ping(); err != nil {
		fmt.Println("connect 2 database failed...")
		return
	}
	//最大连接数
	db.SetMaxOpenConns(10)
	//最大闲置连接数
	db.SetMaxIdleConns(10)
	return nil
}

func insertSourceRow(paramSplit []string) {
	sqlStr := "INSERT INTO tb_device_type_source" +
		"(svr_class, svr_subclass, svr_type, svr_version, cpu_num, ram_num, hdd_size, ssd_size, gpu_card_type, gpu_card_num)" +
		"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?);"
	res, err := db.Exec(sqlStr, paramSplit[0], paramSplit[1], paramSplit[2], paramSplit[3], parseStrToInt(paramSplit[4]),
		parseStrToInt(paramSplit[5]), parseStrToInt(paramSplit[6]), parseStrToInt(paramSplit[7]), paramSplit[8], parseStrToInt(paramSplit[9]))
	if err != nil {
		log.Printf("update failed err : %v\n", err)
	}
	affectedNum, err := res.RowsAffected()
	if err != nil {
		log.Printf("update RowsAffected failed err : %v\n", err)
	}
	log.Println("受影响的行数=", affectedNum)
}

//直接传递sql进行执行, 效率偏低, 且存在sql注入问题
func main() {
	if err := initializeDatabase(); err != nil {
		panic(err)
	}
	fmt.Println("connected")

	readDeviceSourceFile()

}

func readDeviceSourceFile() map[string]string {
	recordMap := map[string]string{}
	const filename = "D:\\code\\go\\go-learn\\go-project\\mysql-read-file\\source.txt"
	if contents, err := ioutil.ReadFile(filename); err == nil {
		recordStr := string(contents)
		paramLine := strings.Split(recordStr, "\r\n")
		for _, str := range paramLine {
			paramSplit := strings.Split(str, ",")
			fmt.Println(paramSplit)
			insertSourceRow(paramSplit)
		}
	} else {
		fmt.Println("print file err: ", err)
	}
	return recordMap
}

func parseStrToInt(str string) int {
	if str != "" {
		tmpInt64, _ := strconv.ParseInt(str, 10, 64)
		return int(tmpInt64)
	}
	return 0
}
